package com.pp.demo.common.exception;

import com.pp.demo.common.constant.CommonErrorCode;
import com.pp.demo.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage(), e);
        return Result.failure(e.getErrorCode());
    }

    /**
     * 处理参数校验异常（@Validated 方法参数校验失败）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String errorMessage = fieldErrors.stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));
        log.error("参数校验异常: {}", errorMessage, e);
        return Result.failure(CommonErrorCode.PARAM_ERROR.getCode(), errorMessage);
    }

    /**
     * 处理路径参数校验异常（@PathVariable 校验失败）
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String errorMessage = violations.stream()
                .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
                .collect(Collectors.joining("; "));
        log.error("路径参数校验异常: {}", errorMessage, e);
        return Result.failure(CommonErrorCode.PARAM_ERROR.getCode(), errorMessage);
    }

    /**
     * 处理表单参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Result<?> handleBindException(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String errorMessage = fieldErrors.stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));
        log.error("表单参数绑定异常: {}", errorMessage, e);
        return Result.failure(CommonErrorCode.PARAM_ERROR.getCode(), errorMessage);
    }

    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("请求方法不支持: {}", e.getMessage(), e);
        return Result.failure(CommonErrorCode.METHOD_NOT_SUPPORTED.getCode(), e.getMessage());
    }

    /**
     * 处理请求参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<?> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        log.error("参数类型不匹配: {}", e.getMessage(), e);
        String errorMessage = String.format("参数 [%s] 类型错误，期望类型 [%s]",
                e.getName(), e.getRequiredType().getSimpleName());
        return Result.failure(CommonErrorCode.PARAM_ERROR.getCode(), errorMessage);
    }

    /**
     * 处理缺少请求参数异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<?> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("缺少请求参数: {}", e.getMessage(), e);
        String errorMessage = String.format("缺少必要的请求参数 [%s]，类型为 [%s]",
                e.getParameterName(), e.getParameterType());
        return Result.failure(CommonErrorCode.PARAM_ERROR.getCode(), errorMessage);
    }

    /**
     * 处理请求体解析异常（如JSON格式错误）
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("请求体解析异常: {}", e.getMessage(), e);
        return Result.failure(CommonErrorCode.PARAM_ERROR.getCode(), "请求体格式错误，请检查JSON格式");
    }

    /**
     * 处理未定义的其他异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        log.error("系统内部异常: {}", e.getMessage(), e);
        return Result.failure(CommonErrorCode.SYSTEM_ERROR.getCode(), e.getMessage()); // 系统繁忙，请稍后重试
    }
}
